package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.PaperTrailListAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPaperPreviewActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtPaperListBinding
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.ClassFlag
import com.lancoo.znbkxx.teacher.model.data.PaperTrailSection
import com.lancoo.znbkxx.teacher.ui.activity.BasicPaperActivity
import com.lancoo.znbkxx.teacher.ui.activity.SearchActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.AnswerTimeEditPopupWindow
import com.lancoo.znbkxx.teacher.widget.PublishPopupWindow
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.android.synthetic.main.fmt_paper_list.*
import kotlinx.android.synthetic.main.view_edit_answer_time.view.*
import paperToChaKanChengJi.CheckScoreActivity

/**
 * Created by wealive on 2021/3/25.
 *
 *
 */
class BasicPaperFragment : BaseVMFragment<PaperViewModel, FmtPaperListBinding>(),
    View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
    BaseQuickAdapter.OnItemChildClickListener {
    private val from by lazy { requireArguments().getString("from") }
    private val layer by lazy { requireArguments().getInt("layer") }
    var publish = -1
    var finish = -1
    var searchInfo = ""
    private val paperList = mutableListOf<PaperTrailSection>()
    private val classFlagList = mutableListOf<ClassFlag>()
    private lateinit var paperAdapter: PaperTrailListAdapter
    private var position: Int = 0
    private var type = 0
    private var pageSize = 10
    private var totalCount = 0
    private var timeEditWindow: AnswerTimeEditPopupWindow? = null

    //    private val timeEditWindow by lazy {
//        AnswerTimeEditPopupWindow(requireContext(), this)
//    }
    private val publishWindow by lazy {
        PublishPopupWindow(classFlagList, requireContext(), this)
    }
    private val loadingDialog by lazy {
        LoadingDailog.Builder(requireContext()).setMessage("发布中...").setCancelOutside(false)
            .setCancelable(false).create()
    }
    private val editLoadingDialog by lazy {
        LoadingDailog.Builder(requireContext()).setMessage("修改中...").setCancelOutside(false)
            .setCancelable(false).create()
    }

    override fun providerContext(): Any? {
        return this
    }

    override fun providerVMClass(): Class<PaperViewModel>? {
        return PaperViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_paper_list
    }

    override fun initView() {
        publish = requireArguments().getInt("publish", -1)
        finish = requireArguments().getInt("finish", -1)
        searchInfo = requireArguments().getString("searchInfo", "")
        initList()
    }

    private fun initList() {
        pageSize = 10
        paperAdapter = PaperTrailListAdapter(R.layout.item_paper_trail_header, paperList, true)
        paperAdapter.onItemClickListener = this
        paperAdapter.onItemChildClickListener = this
        val emptyView = layoutInflater.inflate(R.layout.adapter_item_empty, null)
        paperAdapter.emptyView = emptyView
        val manager = LinearLayoutManager(requireContext())
        val hashMap = hashMapOf<String, Int>()
        hashMap[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 12f)
//        hashMap[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
//        hashMap[SpacesItemDecoration.BOTTOM_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        rv_paper.addItemDecoration(SpacesItemDecoration(hashMap))
        rv_paper.adapter = paperAdapter
        rv_paper.layoutManager = manager
        swipe_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageSize = 10
                initPaper(publish, finish, searchInfo)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (totalCount >= pageSize) {
                    pageSize += 10
                    initPaper(publish, finish, searchInfo)
                }
            }
        })
    }

    private fun release(position: Int) {
        val setId = paperList[position].t.SetID
        val paperId = paperList[position].t.PaperID
        val layer = paperList[position].t.Layer
        val classList = classFlagList.filter { it.checked }
        if (classList.isNullOrEmpty()) {
            MyToast.showToast("请选择发布班级")
            return
        }
        loadingDialog.show()
//        classList.forEach {
//            it.Layer = layer
//            it.SetID = setId
//            it.state = state
//        }
        viewModel.releaseAuditPaper(
            setId, Ext.GLOBAL_GRADE,
            CurrentUser.Token, mutableListOf(paperId), publishWindow.getStartTime(),
            publishWindow.getEndTime(),
            classList.toMutableList(), CurrentUser.UserID, CurrentUser.SchoolID, layer, -1,
            CurrentUser.UserName
        )
    }

    fun initPaper(publish: Int, finish: Int, searchInfo: String) {
        viewModel.getMobilePaperList(
            Ext.COURSE_CLASSID, publish, finish, layer,
            1, pageSize, CurrentUser.SchoolID,
            CurrentUser.Token, CurrentUser.UserID, searchInfo
        )
    }

    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.mPaperTrailInfo.observe(this, Observer {
            if (from == "basic") (activity as BasicPaperActivity).loadingDialog.dismiss() else
                (activity as SearchActivity).loadingDialog.dismiss()
            totalCount = it.Count
            paperList.clear()
            it.List.forEach { paperTrail ->
                val sectionHeader = PaperTrailSection(true, paperTrail.CreateTime)
                paperList.add(sectionHeader)
                paperTrail.PaperList.forEach { paperTime ->
                    val section = PaperTrailSection(paperTime)
                    paperList.add(section)
                }
            }
            paperAdapter.setNewData(paperList)
            swipe_layout.finishRefresh()
            swipe_layout.setEnableLoadMore(pageSize < totalCount)
            if (pageSize == it.Count) {
                swipe_layout.finishLoadMoreWithNoMoreData()
            } else {
                swipe_layout.finishLoadMore()
            }
        })
        viewModel.success.observe(this, Observer {
            loadingDialog.dismiss()
            if (it.ReleaseResult) {
                publishWindow.dismiss()
                val publishDialog = PublishResultDialog().apply {
                    arguments = bundleOf().apply {
                        putParcelableArrayList("release", it.ClassEffectiveList)
                    }
                }
                publishDialog.show(parentFragmentManager, "")
                OperationHelp.operationLog(1, activity)
                initPaper(publish, finish, searchInfo)
            } else {
                MyToast.showToast("发布失败")
            }
        })
        viewModel.mEditDurationInfo.observe(this, Observer {
            editLoadingDialog.dismiss()
            when (it) {
                false -> {
                    MyToast.showToast("试卷已到期，无法修改作答期限")
                }
                true -> {
                    MyToast.showToast("修改成功")
                    timeEditWindow?.dismiss()
                    initPaper(publish, finish, searchInfo)
                }
            }
        })
        viewModel.mSubmittedInfo.observe(this, Observer {
            val stuProgressDialog = StuProgressDialog().apply {
                arguments = bundleOf(Pair("info", it), Pair("type", type))
            }
            stuProgressDialog.show(parentFragmentManager, "")
        })
        viewModel.mClassFlag.observe(this, Observer {
            val unPublishedList = it.filter { classFlag -> !classFlag.IsRelease }
            if (unPublishedList.isEmpty()) {
                MyToast.showToast("全部班级已经发布")
                return@Observer
            }
            classFlagList.clear()
            classFlagList.addAll(it)
            publishWindow.setOnDismissListener { dismissAnimation() }
            publishWindow.adapter.notifyDataSetChanged()
            publishWindow.showAtLocation(rv_paper, Gravity.BOTTOM, 0, 0)
            showAnimation()
        })
        viewModel.mHastenCall.observe(this, Observer {
            when (it) {
                0 -> MyToast.showToast("催交作业失败")
                1 -> MyToast.showToast("催交作业成功")
                else -> initPaper(publish, finish, searchInfo)
            }
        })
        viewModel.mErrorMsg.observe(this, Observer {
            loadingDialog.dismiss()
            editLoadingDialog.dismiss()
            MyToast.showToast(it)
        })
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (adapter) {
            is PaperTrailListAdapter -> {
                val paperId = adapter.data[position].t.PaperID
                val setId = adapter.data[position].t.SetID
                AibkPaperPreviewActivity.launch(requireActivity(), paperId, setId, false)
            }
        }
    }

    @SuppressLint("SetTextI18n")

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val setId = paperList[position].t.SetID
        val paperId = paperList[position].t.PaperID
        val paperName = paperList[position].t.PaperName
        val layer = paperList[position].t.Layer
        val startTime = paperList[position].t.StartTime
        val endTime = paperList[position].t.EndTime
        val intent = Intent()
        intent.putExtra("setId", setId)
        intent.putExtra("paperId", paperId)
        intent.putExtra("layer", layer)
        when (view?.id) {
            R.id.tv_detail -> {
                if (paperList[position].t.State == 2) {
                    return
                }
                intent.putExtra("paperName", paperName)
                intent.setClass(requireActivity(), CheckScoreActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_comment -> {
                if (paperList[position].t.EvalCount == 0) {
                    return
                }
                AibkQuesMarkActivity.launch(
                    requireActivity(), setId, Ext.STU_ID, paperId,
                    paperName,
                    false
                )
            }
            R.id.tv_publish -> {
                this.position = position
                viewModel.getGradeClassWithPaperState(
                    Ext.GLOBAL_GRADE, CurrentUser.SchoolID, setId,
                    paperId, CurrentUser.Token, CurrentUser.UserID
                )
            }
            R.id.tv_time -> {
                timeEditWindow =
                    AnswerTimeEditPopupWindow(requireContext(), startTime, endTime, this)
                timeEditWindow!!.setOnDismissListener { dismissAnimation() }
                timeEditWindow!!.showAtLocation(rv_paper, Gravity.BOTTOM, 0, 0)
                showAnimation()
                this.position = position
                val item = adapter?.getViewByPosition(
                    rv_paper,
                    position + adapter.headerLayoutCount, R.id.tv_time
                ) as TextView
                timeEditWindow!!.contentView.tv_answerTime.text = "当前作答期限：${item.text}"
            }
            R.id.tv_submited, R.id.tv_total, R.id.tv_finished -> {
                type = 0
                viewModel.getStuProgress(
                    paperId,
                    Ext.COURSE_CLASSID, CurrentUser.SchoolID, CurrentUser.Token,
                    CurrentUser.UserID
                )
            }
            R.id.tv_commented, R.id.tv_comment_num, R.id.tv_comment_total_num -> {
                type = 1
                viewModel.getStuProgress(
                    paperId,
                    Ext.COURSE_CLASSID, CurrentUser.SchoolID, CurrentUser.Token,
                    CurrentUser.UserID
                )
            }
            R.id.iv_hastencall -> viewModel.doHastenCall(
                CurrentUser.Token, CurrentUser.UserID,
                paperId, setId, Ext.COURSE_CLASSID, paperName, CurrentUser.SchoolID
            )
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_cancel -> publishWindow.dismiss()
            R.id.tv_publish -> {
                if (publishWindow.getEndTime() < publishWindow.getStartTime()) {
                    MyToast.showToast("结束时间不得小于开始时间")
                    return
                }
                release(position)
            }
            R.id.iv_close -> timeEditWindow?.dismiss()
            R.id.tv_confirm -> {
                if (timeEditWindow!!.getEndTime() < timeEditWindow!!.getStartTime()) {
                    MyToast.showToast("结束时间不得小于开始时间")
                    return
                }
                editLoadingDialog.show()
                viewModel.setPaperAnswerDuration(
                    paperList[position].t.PaperID, Ext.COURSE_CLASSID,
                    timeEditWindow!!.getStartTime(),
                    timeEditWindow!!.getEndTime(), CurrentUser.Token,
                    CurrentUser.SchoolID, paperList[position].t.SetID, Ext.GLOBAL_GRADE,
                    CurrentUser.UserID
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        initPaper(publish, finish, searchInfo)
    }
}